<template>
  <div class="kindeditor-component">
    <UncommonWordDialog ref="UncommonWordDialog"/>
    <ImportImageDialog ref="importImageDialog" :uploadPath="imgUploadPath"/>
    <ImportVideoDialog ref="importVideoDialog" :videoUploadPath="videoUploadPath"/>
    <ImportAudioDialog ref="importAudioDialog" :audioUploadPath="audioUploadPath"/>
    <textarea :id="id" v-model="content"></textarea>
  </div>
</template>

<script>
import UncommonWordDialog from "./UncommonWordDialog";
import ImportImageDialog from "./ImportImageDialog";
import ImportVideoDialog from "./ImportVideoDialog";
import ImportAudioDialog from "./ImportAudioDialog";
import '../../../static/kindeditor/kindeditor-all';
import CONST from "../../const";

export default {
  components: {
    UncommonWordDialog,
    ImportImageDialog,
    ImportVideoDialog,
    ImportAudioDialog
  },
  name: 'KindEditor',
  data() {
    return {
      editor: null,
      imgUploadPath: 'image/' + this.uploadPath,
      videoUploadPath: 'video/' + this.uploadPath,
      audioUploadPath: 'audio/' + this.uploadPath,
    }
  },
  props: {
    placeholder: {
      type: String,
      default: '请输入'
    },
    uploadPath: {
      type: String,
      default: 'tmp'
    },
    value: {},
    editorType: {
      type: String,
      default: 'RichEditor'
    },
    content: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: () => UTIL.generateSfId()
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: Number
    },
    minWidth: {
      type: Number,
      default: 200
    },
    minHeight: {
      type: Number
    },
    items: {
      type: Array,
      default: function () {
        return [
          'source', '|',
          'justifyleft', 'justifycenter', 'justifyright', '|',
          'bold', 'italic', 'underline', 'strikethrough', '|',
          'formatblock', 'contexttype',
          'bordertype',
          'subscript', 'superscript', '|',
          'importimage', 'importaudio', 'importvideo', 'fullscreen'
        ]
      }
    },
    noDisableItems: {
      type: Array,
      default: function () {
        return ['source', 'fullscreen']
      }
    },
    filterMode: {
      type: Boolean,
      default: true
    },
    htmlTags: {
      type: Object,
      default: function () {
        return {
          section: ['id', 'name', 'class', 'style', 'data-role'],
          font: ['color', 'size', 'face', '.background-color'],
          div: ['class', 'align'],
          table: ['class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align'],
          'td,th': ['class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor'],
          a: ['class', 'href', 'target', 'name'],
          img: ['class', 'id', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '/',
            'data-similar-word', 'data-bz-id', 'data-additional', 'data-classification'],
          hr: ['class', '/'],
          // br: ['/'],
          'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6': ['class', 'id'],
          'tbody,tr,strong,b,sub,sup,em,i,u,strike': [],
          'audio,video': ['id', 'class', 'src', 'controls', 'preload'],
        }
      }
    },
    wellFormatMode: {
      type: Boolean,
      default: true
    },
    resizeType: {
      type: Number,
      default: 2
    },
    themeType: {
      type: String,
      default: 'default'
    },
    langType: {
      type: String,
      default: 'zh-CN'
    },
    designMode: {
      type: Boolean,
      default: true
    },
    fullscreenMode: {
      type: Boolean,
      default: false
    },
    basePath: {
      type: String,
      default: CONST.ENV.STATIC_PATH + 'kindeditor/'
    },
    themesPath: {
      type: String
    },
    pluginsPath: {
      type: String
    },
    langPath: {
      type: String
    },
    minChangeSize: {
      type: Number,
      default: 5
    },
    loadStyleMode: {
      type: Boolean,
      default: true
    },
    urlType: {
      type: String,
      default: ''
    },
    newlineTag: {
      type: String,
      default: 'p'
    },
    pasteType: {
      type: Number,
      default: 2
    },
    dialogAlignType: {
      type: String,
      default: 'page'
    },
    shadowMode: {
      type: Boolean,
      default: true
    },
    zIndex: {
      type: Number,
      default: 811213
    },
    useContextmenu: {
      type: Boolean,
      default: true
    },
    syncType: {
      type: String,
      default: 'form'
    },
    indentChar: {
      type: String,
      default: '\t'
    },
    cssPath: {
      type: [String, Array],
      default: CONST.ENV.STATIC_PATH + 'kindeditor/css/richeditor.css'
    },
    cssData: {
      type: String,
    },
    bodyClass: {
      type: String,
      default: 'ke-content'
    },
    colorTable: {
      type: Array
    },
    afterCreate: {
      type: Function
    },
    afterChange: {
      type: Function
    },
    afterTab: {
      type: Function
    },
    afterUpload: {
      type: Function
    },
    uploadJson: {
      type: String,
      default: '/pmph/action/richEditor/richEditorImgUpload'
    },
    fileManagerJson: {
      type: String
    },
    allowPreviewEmoticons: {
      type: Boolean,
      default: true
    },
    allowImageUpload: {
      type: Boolean,
      default: true
    },
    allowFlashUpload: {
      type: Boolean,
      default: true
    },
    allowMediaUpload: {
      type: Boolean,
      default: true
    },
    allowFileUpload: {
      type: Boolean,
      default: true
    },
    allowFileManager: {
      type: Boolean,
      default: false
    },
    fontSizeTable: {
      type: Array,
      default: function () {
        return ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px']
      }
    },
    imageTabIndex: {
      type: Number,
      default: 0
    },
    formatUploadUrl: {
      type: Boolean,
      default: true
    },
    fullscreenShortcut: {
      type: Boolean,
      default: false
    },
    extraFileUploadParams: {
      type: Object,
      default: function () {
        return {}
      }
    },
    filePostName: {
      type: String,
      default: 'imgFile'
    },
    fillDescAfterUploadImage: {
      type: Boolean,
      default: false
    },
    afterSelectFile: {
      type: Function
    },
    pagebreakHtml: {
      type: String,
      default: '<hr style="page-break-after: always;" class="ke-pagebreak" />'
    },
    allowImageRemote: {
      type: Boolean,
      default: false
    },
    autoHeightMode: {
      type: Boolean,
      default: true
    },
    fixToolBar: {
      type: Boolean,
      default: false
    },
    tabIndex: {
      type: Number
    },
    readonly: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    content(val) {
      if (!val) {
        if (this.editor.html() !== this.placeholder) {
          this.editor.html(this.placeholder)
          KindEditor(this.editor.cmd.doc.body).css('color', '#ccc')
        }
      } else if (this.editor.html() !== val) {
        this.editor.html(val)
      }
    },
    editorType() {
      this.editor.html(this.content)
      this.initEditor()
    },
    readonly(val) {
      this.editor.readonly(val)
    }
  },
  mounted() {
    // 初始访问时创建
    this.initEditor()
  },
  /**
   * keep-alive 会用到进入时调用activated 离开时调用deactivated
   * 初始访问 created、mounted 切换时deactivated 再次进入时 activated
   */
  activated() {
    // keep-alive 进入时创建
    this.initEditor()
  },
  deactivated() {
    // keep-alive 离开时移除
    this.removeEditor()
  },
  methods: {
    importAudio() {
      var _this = this
      let focusNode = this.editor.cmd.sel.focusNode
      if (focusNode && focusNode.tagName === 'AUDIO') {
        let audio = focusNode.parentElement.firstElementChild
        // 音频类型;
        this.$refs.importAudioDialog.field.fieldValue.type = audio.getAttribute('class') || ''
        let cnt_doc = this.editor.cmd.doc
        if (cnt_doc.getElementById('v_title_' + audio.getAttribute('id'))) {
          let v_title_str = cnt_doc.getElementById('v_title_' + audio.getAttribute('id')).innerHTML
          this.$refs.importAudioDialog.field.fieldValue.title = v_title_str
        }
        Array.from(audio.parentElement.getElementsByTagName('AUDIO')).forEach(function (item) {
          _this.$refs.importAudioDialog.field.fieldValue.paths.push(item.getAttribute('src'))
        })
        this.$refs.importAudioDialog.title = '修改音频'
      }
      this.$refs.importAudioDialog.visible = true
    },
    importVideo() {
      var _this = this
      let focusNode = this.editor.cmd.sel.focusNode
      if (focusNode && focusNode.tagName === 'VIDEO') {
        let video = focusNode.parentElement.firstElementChild
        // 视频类型;
        this.$refs.importVideoDialog.field.fieldValue.type = video.getAttribute('class') || ''
        let cnt_doc = this.editor.cmd.doc
        if (cnt_doc.getElementById('v_title_' + video.getAttribute('id'))) {
          let v_title_str = cnt_doc.getElementById('v_title_' + video.getAttribute('id')).innerHTML
          this.$refs.importVideoDialog.field.fieldValue.title = v_title_str
        }
        Array.from(video.parentElement.getElementsByTagName('VIDEO')).forEach(function (item) {
          _this.$refs.importVideoDialog.field.fieldValue.paths.push(item.getAttribute('src'))
        })
        this.$refs.importVideoDialog.title = '修改视频'
      }
      this.$refs.importVideoDialog.visible = true
    },
    importImage() {
      this.$refs.importImageDialog.visible = true
    },
    removeEditor() {
      window.KindEditor.remove('#' + this.id)
    },
    initEditor() {
      var _this = this
      _this.removeEditor()
      let cssData = ''
      if (this.editorType === 'RichEditor')
        cssData = '.h1 {font-size: 25px; font-weight: bold; color: red;} ' +
          '.h2 {font-size: 25px; font-weight: bold; color: green;} ' +
          '.h3 {font-size: 25px; font-weight: bold; color: blue;} ' +
          '.h4 {font-size: 20px; font-weight: bold; color: red;} ' +
          '.h5 {font-size: 20px; font-weight: bold; color: green;} ' +
          '.h6 {font-size: 20px; font-weight: bold; color: blue;} ' +
          'body, p, td{ font-size: 16px; } p{text-indent: 28px;} '
      else if (this.editorType === 'Input')
        cssData = 'body{ font-size: 16px; overflow: hidden; white-space: nowrap;} p{text-indent: 0px;}'
      else if (this.editorType === 'Textarea')
        cssData = 'body{ font-size: 16px;} p{text-indent: 0px;}'
      let items = _this.items
      // 高度;
      let calHeight = _this.height
      if (!calHeight) {
        calHeight = _this.editorType === 'RichEditor' ? 200 : _this.editorType === 'Textarea' ? 80 : 35
      }
      // 最小高度;
      let calMinHeight = _this.minHeight
      if (!calMinHeight) {
        calMinHeight = calHeight
      }
      _this.editor = window.KindEditor.create('#' + this.id, {
        width: _this.width,
        height: calHeight,
        minWidth: _this.minWidth,
        minHeight: calMinHeight,
        items: items,
        noDisableItems: _this.noDisableItems,
        filterMode: _this.filterMode,
        htmlTags: _this.htmlTags,
        wellFormatMode: _this.wellFormatMode,
        resizeType: _this.resizeType,
        themeType: _this.themeType,
        langType: _this.langType,
        designMode: _this.designMode,
        fullscreenMode: _this.fullscreenMode,
        basePath: _this.basePath,
        themesPath: _this.themesPath,
        pluginsPath: _this.pluginsPath,
        langPath: _this.langPath,
        minChangeSize: _this.minChangeSize,
        loadStyleMode: _this.loadStyleMode,
        urlType: _this.urlType,
        newlineTag: _this.newlineTag,
        pasteType: _this.pasteType,
        dialogAlignType: _this.dialogAlignType,
        shadowMode: _this.shadowMode,
        zIndex: _this.zIndex,
        useContextmenu: _this.useContextmenu,
        syncType: _this.syncType,
        indentChar: _this.indentChar,
        cssPath: _this.cssPath,
        bodyClass: _this.bodyClass,
        colorTable: _this.colorTable,
        editorType: _this.editorType,
        cssData: cssData,
        readonlyMode: _this.readonly,
        afterCreate() {
          if (!this.edit.html()) {
            this.edit.html(_this.placeholder);
            KindEditor(this.edit.cmd.doc.body).css('color', '#ccc')
          }
          if (this.editorType == 'Input' || this.editorType == 'Textarea') {
            this.toolbar.hide(true)
            this.statusbar.hide(true)
            this.edit.div.css('margin', '0px 4px')
          }
          this.container.css('border', '1px solid #DCDFE6')
          this.container.css('border-radius', '4px')
        },
        afterChange: function () {
          if (this.edit.html() !== _this.placeholder) {
            KindEditor(this.edit.cmd.doc.body).css('color', null)
          }
          // 查找audio, 绑定 focus 事件
          let audioElementList = this.edit.cmd.doc.getElementsByTagName("AUDIO")
          for (let audioElement of audioElementList) {
            audioElement.addEventListener("focus", (e) => {
                KindEditor('.crtSelect', this.edit.cmd.doc).removeClass('crtSelect')
                this.edit.cmd.selection(true)
                this.edit.cmd.range.selectNode(e.target)
                this.edit.cmd.select()
                KindEditor(e.target).addClass('crtSelect')
                e.preventDefault()
            })
          }
        },
        afterTab: _this.afterTab,
        afterFocus: function () {
          if (this.edit.html() == _this.placeholder) {
            this.edit.html('')
            KindEditor(this.edit.cmd.doc.body).css('color', null)
          }
        },
        afterBlur: function () {
          if (this.edit.html() !== _this.placeholder) {
            var bodyElement = this.edit.cmd.doc.body
            if (this.editorType === 'RichEditor') {
              // 解决body下直接是文本问题;
              var nodeList = bodyElement.childNodes
              for (let i = 0; i < nodeList.length; i++) {
                var cntNode = nodeList[i];
                if (cntNode.tagName != 'DIV' && cntNode.tagName != 'P') {
                  var newEl = document.createElement('P')
                  bodyElement.insertBefore(newEl, cntNode)
                  newEl.appendChild(cntNode)
                  while (true) {
                    cntNode = newEl.nextSibling
                    if (!cntNode || cntNode.tagName == 'DIV' || cntNode.tagName == 'P') {
                      break
                    } else {
                      newEl.appendChild(cntNode)
                    }
                  }
                }
              }
              // 如果相连多个空行, 只保留一个;
              let pEleList = bodyElement.getElementsByTagName("P")
              let pEleLength = pEleList.length
              for (let i = pEleLength - 1; i > 0; i--) {
                let pEle = pEleList[i]
                if (pEle.innerHTML === '') {
                  pEle.remove()
                }
                else if (pEle.innerHTML === '<br>'
                  && pEle.previousSibling.innerHTML === '<br>') {
                  pEle.remove()
                }
              }
            }
            // 文本域, 如果是单行, 则去除外层p标签
            else if (this.editorType === 'Textarea') {
              var pElements = bodyElement.getElementsByTagName('P')
              if (pElements.length === 1) {
                var pEl = pElements[0]
                while (pEl.firstChild) {
                  bodyElement.insertBefore(pEl.firstChild, pEl)
                }
                bodyElement.removeChild(pEl)
              }
            }
          }
          if (!this.edit.html()) {
            this.edit.html(_this.placeholder)
            KindEditor(this.edit.cmd.doc.body).css('color', '#ccc')
            _this.$emit('update:content', '')
          } else {
            _this.$emit('update:content', this.edit.html())
          }
        },
        afterUpload: _this.afterUpload,
        uploadJson: _this.uploadJson,
        fileManagerJson: _this.fileManagerJson,
        allowPreviewEmoticons: _this.allowPreviewEmoticons,
        allowImageUpload: _this.allowImageUpload,
        allowFlashUpload: _this.allowFlashUpload,
        allowMediaUpload: _this.allowMediaUpload,
        allowFileUpload: _this.allowFileUpload,
        allowFileManager: _this.allowFileManager,
        fontSizeTable: _this.fontSizeTable,
        imageTabIndex: _this.imageTabIndex,
        formatUploadUrl: _this.formatUploadUrl,
        fullscreenShortcut: _this.fullscreenShortcut,
        extraFileUploadParams: _this.extraFileUploadParams,
        filePostName: _this.filePostName,
        fillDescAfterUploadImage: _this.fillDescAfterUploadImage,
        afterSelectFile: _this.afterSelectFile,
        pagebreakHtml: _this.pagebreakHtml,
        allowImageRemote: _this.allowImageRemote,
        autoHeightMode: _this.autoHeightMode && this.editorType != 'Input',
        fixToolBar: _this.fixToolBar,
        tabIndex: _this.tabIndex
      })

      _this.editor.addContextmenu({
        title: '添加生僻字',
        iconClass: "ke-icon-word",
        click: function () {
          _this.$refs.UncommonWordDialog.visible = true
          _this.editor.hideMenu();
        },
        cond: function () {
          // 选中video时, selectedHtml() 也为'';
          return !_this.editor.selectedHtml()
            && _this.editor.cmd.sel.focusNode.tagName !== 'VIDEO'
            && _this.editor.cmd.sel.focusNode.tagName !== 'AUDIO'
        }
      })

      _this.editor.addContextmenu({
        title: '删除视频',
        // iconClass: "ke-icon-word",
        click: function () {
          _this.editor.hideMenu()
          let videoEl = KindEditor(_this.editor.cmd.sel.focusNode).parent().first()
          var cnt_doc = _this.editor.cmd.doc
          // 删除原视频标题
          if (cnt_doc.getElementById('v_title_' + videoEl.attr("id"))) {
            cnt_doc.getElementById('v_title_' + videoEl.attr("id")).remove()
          }
          // 删除视频
          videoEl.parent().remove()
        },
        cond: function () {
          return _this.editor.cmd.sel.focusNode.tagName === 'VIDEO'
        }
      })

      _this.editor.addContextmenu({
        title: '删除音频',
        click: function () {
          _this.editor.hideMenu()
          let audioEl = KindEditor(_this.editor.cmd.sel.focusNode).parent().first()
          var cnt_doc = _this.editor.cmd.doc
          // 删除原音频标题
          if (cnt_doc.getElementById('v_title_' + audioEl.attr("id"))) {
            cnt_doc.getElementById('v_title_' + audioEl.attr("id")).remove()
          }
          // 删除音频
          audioEl.parent().remove()
        },
        cond: function () {
          return _this.editor.cmd.sel.focusNode.tagName === 'AUDIO'
        }
      })

      _this.editor.addContextmenu({
        title: '音频属性',
        click: function () {
          _this.editor.hideMenu()
          let audioEl = KindEditor(_this.editor.cmd.sel.focusNode).parent().first()
          var cnt_doc = _this.editor.cmd.doc
          // 删除原音频标题
          let vTitleEl = cnt_doc.getElementById('v_title_' + audioEl.attr("id"))
          if (vTitleEl) {
            var vTitle = vTitleEl.innerHTML
          }
          // 音频标题;
          _this.$refs.importAudioDialog.field.fieldValue.title = vTitle
          // 音频列表;
          audioEl.parent().scan(function (item) {
            if (item.tagName == 'AUDIO') {
              _this.$refs.importAudioDialog.field.fieldValue.paths.push(item.getAttribute('src'))
            }
          })
          _this.$refs.importAudioDialog.title = '修改音频'
          _this.$refs.importAudioDialog.visible = true
        },
        cond: function () {
          return _this.editor.cmd.sel.focusNode.tagName === 'AUDIO'
        }
      })

      _this.editor.addContextmenu({
        title: '视频属性',
        // iconClass: "ke-icon-word",
        click: function () {
          _this.editor.hideMenu()
          let videoEl = KindEditor(_this.editor.cmd.sel.focusNode).parent().first()
          var cnt_doc = _this.editor.cmd.doc
          // 删除原视频标题
          let vTitleEl = cnt_doc.getElementById('v_title_' + videoEl.attr("id"))
          if (vTitleEl) {
            var vTitle = vTitleEl.innerHTML
          }
          // 视频标题;
          _this.$refs.importVideoDialog.field.fieldValue.title = vTitle
          // 视频列表;
          // _this.$refs.importVideoDialog.field.fieldValue.paths = [videoEl[0].getAttribute('src')]
          videoEl.parent().scan(function (item) {
            if (item.tagName == 'VIDEO') {
              _this.$refs.importVideoDialog.field.fieldValue.paths.push(item.getAttribute('src'))
            }
          })
          _this.$refs.importVideoDialog.title = '修改视频'
          _this.$refs.importVideoDialog.visible = true
        },
        cond: function () {
          return _this.editor.cmd.sel.focusNode.tagName === 'VIDEO'
        }
      })

      _this.editor.addContextmenu({
        title: '上标',
        iconClass: "ke-icon-superscript",
        click: function () {
          _this.editor.clickToolbar('superscript')
          _this.editor.hideMenu()
        },
        cond: function () {
          return _this.editor.cmd.range.toString()
          // && !_this.editor.cmd.state('superscript')
        }
      })

      _this.editor.addContextmenu({
        title: '下标',
        iconClass: "ke-icon-subscript",
        click: function () {
          _this.editor.clickToolbar('subscript')
          _this.editor.hideMenu()
        },
        cond: function () {
          return _this.editor.cmd.range.toString()
          // && !_this.editor.cmd.state('subscript')
        }
      })

      _this.editor.cmd.doc.onpaste = function () {
        // 普通输入框 ctrl + v, 只允许能粘到input框里的内容
        if (_this.editor.editorType == 'Input') {
          var tempInput = document.createElement('input')
          tempInput.value = event.clipboardData.getData('Text')
          _this.editor.insertHtml(tempInput.value)
          return false
        }
        // 文本域 ctrl + v, 只允许能粘到文本域里的内容
        else if (_this.editor.editorType == 'Textarea') {
          var tempTextarea = document.createElement('textarea')
          tempTextarea.value = event.clipboardData.getData('Text')
          _this.editor.insertHtml(tempTextarea.value)
          return false
        }
        // 清理标签;
        setTimeout(function () {
          var imgElementList = _this.editor.cmd.doc.getElementsByTagName('img');
          for (let imgElement of imgElementList) {
            var imgSrc = imgElement.getAttribute('src');
            if (imgSrc.startsWith('file') || imgSrc.startsWith('data')) {
              _this.$message.warning('富文本包含本地图片, 请删除后通过附件上传')
            } else if (imgSrc.startsWith(CONST.ENV.RESOURCE_URL)) {
              imgElement.setAttribute('src', imgSrc.replace(CONST.ENV.RESOURCE_URL, ''))
              imgSrc = imgElement.getAttribute('src')
            } else if (imgSrc.startsWith('http')) {
              _this.$message.warning('富文本包含外网图片, 请删除后通过附件上传')
            }
          }
          _this.editor.afterBlur()
        }, 100)
      }

      _this.editor.plugin.image = {
        edit: function () {
          _this.editor.afterFocus()
          if (_this.editor.plugin.getSelectedImage()) {
            var img = _this.editor.plugin.getSelectedImage()
            // 如果不是行内图, 则有可能是组图, 取组图的第一张图片属性;
            if (img.attr('class').indexOf('hnt') == -1) {
              img = img.parent().first()
            }
            // 图片类型;
            var image_type_str = 'rw_img ' + img.attr('class').split(' ')[1]
            _this.$refs.importImageDialog.field.fieldValue.type = image_type_str
            // 补充类型;
            var additional = img[0].getAttribute('data-additional')
            if (additional === null) {
              additional = img.attr('class').split(' ')[2]
            }
            _this.$refs.importImageDialog.field.fieldValue.additional = additional || ''
            // 图片分类;
            _this.$refs.importImageDialog.field.fieldValue.classification = img.attr('data-classification') || ''
            var p_title_str = ''
            var p_note_str = ''
            var cnt_doc = _this.editor.cmd.doc
            if ('rw_img table' == image_type_str) {
              // 表题表注;
              if (cnt_doc.getElementById('t_title_' + img.attr('id'))) {
                p_title_str = cnt_doc.getElementById('t_title_' + img.attr('id')).innerHTML
              }
              if (cnt_doc.getElementById('t_note_' + img.attr('id'))) {
                p_note_str = cnt_doc.getElementById('t_note_' + img.attr('id')).innerHTML
              }
            }
            // 图注/表注;
            else {
              if (cnt_doc.getElementById('p_title_' + img.attr('id'))) {
                p_title_str = cnt_doc.getElementById('p_title_' + img.attr('id')).innerHTML
              }
              if (cnt_doc.getElementById('p_note_' + img.attr('id'))) {
                p_note_str = cnt_doc.getElementById('p_note_' + img.attr('id')).innerHTML
              }
            }
            // 图题;
            _this.$refs.importImageDialog.field.fieldValue.title = p_title_str
            // 图注;
            _this.$refs.importImageDialog.field.fieldValue.comment = p_note_str
            img.parent().scan(function (item) {
              if (item.tagName == 'IMG') {
                _this.$refs.importImageDialog.field.fieldValue.paths.push(item.getAttribute('src'))
              }
            })
            _this.$refs.importImageDialog.title = '修改图片'
          }
          _this.$refs.importImageDialog.visible = true
        },
        'delete': function () {
          var target = _this.editor.plugin.getSelectedImage();
          // 删除原图题图注
          var cnt_doc = _this.editor.cmd.doc
          if (cnt_doc.getElementById('p_title_' + target.attr('id'))) {
            cnt_doc.getElementById('p_title_' + target.attr('id')).remove()
          }
          if (cnt_doc.getElementById('p_note_' + target.attr('id'))) {
            cnt_doc.getElementById('p_note_' + target.attr('id')).remove()
          }
          if (cnt_doc.getElementById('t_title_' + target.attr('id'))) {
            cnt_doc.getElementById('t_title_' + target.attr('id')).remove()
          }
          if (cnt_doc.getElementById('t_note_' + target.attr('id'))) {
            cnt_doc.getElementById('t_note_' + target.attr('id')).remove()
          }
          // 如果图片为非行内图, 且父标签为p, 则删除父标签;
          if (target.attr('class').indexOf('hnt') == -1 && target.parent().name == 'p') {
            target = target.parent();
          }
          target.remove();
          _this.editor.addBookmark();
          setTimeout(function () {
            _this.editor.hideDialog().focus();
          }, 0);
        }
      };
      _this.editor.clickToolbar('importimage', _this.editor.plugin.image.edit);
      _this.editor.clickToolbar('importvideo', _this.importVideo);
      _this.editor.clickToolbar('importaudio', _this.importAudio);
    }
  }
}
</script>
